import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:tiktokadult/hj_model/cartoon_media_info.dart';
import 'package:tiktokadult/hj_model/video_model.dart';
import 'package:tiktokadult/hj_page/cartoon_business/acg_widget_item.dart';
import 'package:tiktokadult/hj_page/video/view/video_detail_bottom_menu.dart';
import 'package:tiktokadult/hj_page/video/view/video_detail_info_widget.dart';
import 'package:tiktokadult/hj_utils/api_service/acg_service.dart';
import 'package:tiktokadult/hj_utils/api_service/common_service.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/banner/ads_grid_view_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tiktokadult/tools_base/loading/l_error_widget.dart';
import 'package:tiktokadult/tools_base/loading/loading_center_widget.dart';
import 'package:video_player/video_player.dart';

import '../../../hj_utils/global.dart';
import '../../../routers/jump_router.dart';
import '../../../tools_base/debug_log.dart';
import '../../../tools_base/refresh/pull_refresh.dart';
import '../../home_business/home_cell_style/video_simple_cell_widget.dart';

/// 视屏播放页数据详情
class VideoDetailView extends StatefulWidget {
  final VideoModel? model;
  final VideoPlayerController? controller;
  final Function? callback;
  final Function(VideoModel model)? vmCallback;
  final Function(int isCodeless)? unCodeCallback; // 1:源视频,2:中文字幕,3:破解版

  const VideoDetailView({
    super.key,
    this.model,
    this.controller,
    this.callback,
    this.vmCallback,
    this.unCodeCallback,
  });

  @override
  State<StatefulWidget> createState() {
    return _VideoDetailViewState();
  }
}

class _VideoDetailViewState extends State<VideoDetailView> with AutomaticKeepAliveClientMixin {
  RefreshController? refreshController;

  VideoPlayerController? get vpController => widget.controller;

  VideoModel? get videoModel => widget.model;

  List<VideoModel>? moreVideoArr;
  List<CartoonMediaInfo>? moreAcgArr;
  int currentPage = 1;
  int selectMenuIndex = 0;
  bool isLoading = true;

  List<String> get menuTitles => ["视频", "动漫", "漫画"];

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    if( videoModel?.id?.isNotEmpty == true) {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        _loadVideoData(0);
      });
    }
  }

  Future<bool> safeFlashUI() async {
    if (!mounted) return false;
    if (SchedulerBinding.instance.schedulerPhase != SchedulerPhase.idle) {
      await SchedulerBinding.instance.endOfFrame;
      if (!mounted) return false;
    }
    setState(() {});
    return true;
  }

  void _exchangeMenuIndex(int index) {
    selectMenuIndex = index;
    currentPage = 1;
    isLoading = true;
    moreVideoArr = null;
    moreAcgArr = null;
    safeFlashUI();
    if (index == 0) {
      _loadVideoData(index);
    } else {
      _loadACGData(index);
    }
  }

  void _loadMoreData() {
    if (selectMenuIndex == 0) {
      _loadVideoData(selectMenuIndex, page: currentPage + 1);
    } else {
      _loadACGData(selectMenuIndex, page: currentPage + 1);
    }
  }

  void _loadVideoData(int menuIndex, {int page = 1, int size = 10}) async {
    try {
      final retTemp = await CommonService.getRecommendList(
        pageNumber: page,
        pageSize: size,
        vid: videoModel?.id,
      );
      if (selectMenuIndex != menuIndex) return;
      currentPage = page;
      moreVideoArr ??= [];
      if (currentPage == 1) {
        moreVideoArr?.clear();
      }
      moreVideoArr?.addAll((retTemp?.videos ?? []));
      if (retTemp?.hasNext == true) {
        refreshController?.loadComplete();
      } else {
        refreshController?.loadNoData();
      }
    } catch (e) {
      refreshController?.loadComplete();
      debugLog(e);
    }
    moreVideoArr ??= [];
    isLoading = false;
    safeFlashUI();
  }

  void _loadACGData(int menuIndex, {int page = 1, int size = 10}) async {
    try {
      final retTemp = await ACGService.comicsRecommendList(
        page,
        size,
        mediaId: videoModel?.id,
      );
      if (selectMenuIndex != menuIndex) return;
      currentPage = page;
      moreAcgArr ??= [];
      if (currentPage == 1) {
        moreAcgArr?.clear();
      }
      moreAcgArr?.addAll((retTemp?.list ?? []));
      if (retTemp?.hasNext == true) {
        refreshController?.loadComplete();
      } else {
        refreshController?.loadNoData();
      }
    } catch (e) {
      refreshController?.loadComplete();
      debugLog(e);
    }
    moreAcgArr ??= [];
    isLoading = false;
    safeFlashUI();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return pullYsRefresh(
      // refreshController: refreshController,
      onInit: (ctr) => refreshController = ctr,
      enablePullDown: false,
      enablePullUp: true,
      onLoading: (refreshController) => _loadMoreData(),
      child: CustomScrollView(
        slivers: [
          SliverToBoxAdapter(
            child: Container(
              margin: EdgeInsets.only(left: 12, right: 12),
              child: VideoDetailInfoWidget(
                model: videoModel,
                controller: widget.controller,
              ),
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
              margin: EdgeInsets.fromLTRB(12, 18, 12, 0),
              child: VideoDetailBottomMenu(model: videoModel),
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
              margin: EdgeInsets.fromLTRB(12, 16, 12, 16),
              child: 0.5.line,
            ),
          ),
          // /// 视频播放页广告
          SliverToBoxAdapter(
            child: AdsGridViewWidget(
              6,
              padding: EdgeInsets.only(left: 12, bottom: 16),
              horCount: 5.3,
            ),
          ),
          _buildTitleMenu(),
          SliverToBoxAdapter(child: 12.sizeBoxH),
          _buildMoreList(),
        ],
      ),
    );
  }

  Widget _buildTitleMenu() {
    return SliverToBoxAdapter(
      child: Container(
        alignment: Alignment.center,
        height: 18,
        child: ListView.builder(
          padding: EdgeInsets.zero,
          shrinkWrap: true,
          scrollDirection: Axis.horizontal,
          physics: NeverScrollableScrollPhysics(),
          itemCount: menuTitles.length,
          itemBuilder: (ctx, index) {
            bool isSelected = index == selectMenuIndex;
            return InkWell(
              onTap: () {
                if (!isSelected) {
                  _exchangeMenuIndex(index);
                }
              },
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 16),
                alignment: Alignment.centerLeft,
                child: Text(
                  menuTitles[index],
                  style: TextStyle(
                    color: isSelected ? Color(0xE5FFFFFF) : Color(0x73FFFFFF),
                    fontSize: 14,
                    fontWeight: isSelected ? FontWeight.w500 : FontWeight.w400,
                  ),
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildMoreList() {
    if(isLoading){
      return SliverToBoxAdapter(
        child: Container(
          height: 250,
          child: LoadingCenterWidget(),
        ),
      );
    }else if(selectMenuIndex == 0 && moreVideoArr?.isEmpty == true){
      return SliverToBoxAdapter(
        child: Container(
          height: 250,
          child: CErrorWidget(),
        ),
      );
    }else if(selectMenuIndex != 0 && moreAcgArr?.isEmpty == true){
      return SliverToBoxAdapter(
        child: Container(
          height: 250,
          child: CErrorWidget(),
        ),
      );
    } else if (selectMenuIndex == 0) {
      return SliverPadding(
        padding: EdgeInsets.only(left: 12, right: 12),
        sliver: SliverGrid.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            childAspectRatio: 168 / 142,
            mainAxisSpacing: 12,
            crossAxisSpacing: 6,
          ),
          itemCount: moreVideoArr?.length ?? 0,
          itemBuilder: (context, index) {
            VideoModel acModel = moreVideoArr![index];
            return VideoSimpleCellWidget(
              videoModel: acModel,
              onTap: () {
                if (acModel.sourceURL?.isNotEmpty == true) {
                  if (acModel.id != videoModel?.id) {
                    if ((acModel.playTime ?? 300) < 300) {
                      widget.controller?.pause();
                      pushToVideoPage(videoModel: acModel);
                    } else {
                      widget.vmCallback?.call(acModel);
                    }
                    // pushToReplace(context, VideoPage(model: acModel));
                  } else {
                    showToast("当前视频正在播放");
                  }
                } else {
                  widget.controller?.pause();
                  pushToVideoPage(videoModel: acModel);
                }
              },
            );
          },
        ),
      );
    }else {
      return SliverPadding(
        padding: EdgeInsets.only(left: 12, right: 12),
        sliver: SliverGrid.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            childAspectRatio: 111 / 174,
            mainAxisSpacing: 12,
            crossAxisSpacing: 6,
          ),
          itemCount: moreAcgArr?.length ?? 0,
          itemBuilder: (context, index) {
            CartoonMediaInfo acModel = moreAcgArr![index];
            return AcgItemWidget(
              info: acModel,
              tapCallback: () {
                widget.controller?.pause();
                if (acModel.mediaType == 'video'){
                  VideoModel videoModel = VideoModel(id: acModel.id);
                  videoModel.cover = acModel.coverH;
                  videoModel.videoType = 1;
                  widget.vmCallback?.call(videoModel);
                }else {
                  pushToCartoonPage(acModel);
                }
              },
            );
          },
        ),
      );
    }
  }
}
